﻿using System;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Mail;
using HTT.Library;
using System.IO;
using System.Data.SqlClient;
using System.Web.Caching;
using System.Web.Configuration;
using System.Data.OleDb;


namespace QuanCafe.DataLayer
{
    public class CLSCommon
    {
        static string strControl;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pCtrl"></param>
        /// <param name="pCommandText"></param>
        /// <param name="pValueField"></param>
        /// <param name="pTextField"></param>
        /// <param name="pRowBlank"></param>

        //Long them Cho Chuc Nang IMPORT
        public static string ImpactDB_DataGrid(string strParamUserAction, Object strUserAction, DataGrid dtgGrid, string strSelect, string strActivity, string strProcedureName, string strListID)
        {
            return ImpactDB_DataGrid(strParamUserAction, strUserAction, dtgGrid, strSelect, strActivity, strProcedureName, strListID, false);

        }
        public static string ImpactDB_DataGrid(string strParamUserAction, Object strUserAction, DataGrid dtgGrid, string strSelect, string strActivity, string strProcedureName, string strListID, bool blnUsedLasCol)
        {

            string strmess = "";
            string strErrorID = "";
            DataTable dtObj = new DataTable();
            dtObj = GetDataTable("sp_Common @ObjName=N'" + strProcedureName + "'");
            //SqlTransaction sqlTran;
            SqlConnection cnn = new SqlConnection(ConfigurationSettings.AppSettings["strConnection"]);
            cnn.Open();
            //sqlTran = cnn.BeginTransaction();			
            SqlCommand cmd = new SqlCommand();
            //cmd.Transaction = sqlTran;
            cmd.Connection = cnn;

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = strProcedureName;

            int iCols = dtgGrid.Items.Count;
            ////if blnUsedLasCol = false: last col for file name
            //if (blnUsedLasCol == false)
            //    iCols--;

            try
            {
                for (int i = 0; i < iCols; i++)
                {
                    string[] arrID = strListID.Trim().Split('$');
                    if (((CheckBox)dtgGrid.Items[i].FindControl(strSelect)).Checked == true)
                    {
                        //						System.Web.SessionState Session["ssIDRows"] = "";
                        //						Session["ssIDRows"] = i;
                        try
                        {
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@Activity", SqlDbType.NVarChar, 50).Value = strActivity.Trim();
                            cmd.Parameters.Add(strParamUserAction, SqlDbType.NVarChar, 10).Value = strUserAction;
                            for (int j = 0; j < arrID.Length - 1; j++)
                            {
                                DataRow[] iRow = dtObj.Select("columnname ='@" + arrID.GetValue(j).ToString().Trim() + "'");
                                if (iRow.Length > 0)
                                {
                                    SqlParameter param = new SqlParameter();
                                    param.ParameterName = iRow[0]["columnname"].ToString().Trim();
                                    if (param.ParameterName == "@CNOT1")
                                    {
                                        string x = "";
                                    }
                                    param.SqlDbType = ConvertDataType(iRow[0]["datatype"].ToString().Trim());
                                    param.Size = SafeDataInteger(iRow[0]["size"].ToString().Trim());
                                    //Value
                                    string strValue = dtgGrid.Items[i].Cells[j].Text.Trim();

                                    if (param.SqlDbType == SqlDbType.Real)
                                        strValue = strValue.Replace(",", "");

                                    if (strValue.Replace("&nbsp;", "").Trim() == "")
                                        param.Value = DBNull.Value;
                                    else
                                    {
                                        if (param.SqlDbType == SqlDbType.Bit)
                                            param.Value = (strValue == "True" || strValue == "1") ? 1 : 0;
                                        else
                                            param.Value = strValue;
                                    }
                                    cmd.Parameters.Add(param);
                                }
                            }
                           strmess = "";
                           cmd.Parameters.Add("@thongbao", SqlDbType.NVarChar, 100).Direction = ParameterDirection.InputOutput;
                           cmd.ExecuteNonQuery();
                           strmess = cmd.Parameters["@thongbao"].Value.ToString();
                           if (strmess != "")
                               strErrorID += i.ToString() + "@" + strmess + "$";
                        }
                        catch (Exception exp)
                        {
                            if (exp.Message.Length > 300)
                                strErrorID += i.ToString() + "@" + exp.Message.Replace("@", "").Substring(0, 300) + "$";
                            else
                                strErrorID += i.ToString() + "@" + exp.Message.Replace("@", "") + "$";

                        }
                    }
                }

                //if (sqlTran != null ) sqlTran.Commit();
                if (strErrorID == "")
                    return "Successful!";
                else
                    return strErrorID;
            }
            catch (Exception exp)
            {
                //if (sqlTran != null) sqlTran.Rollback();
                return exp.Message;
            }
        }
        public static void ShowMessageToDataGrid(string strErrorID, string strCssClass, string lblErrorDtg, DataGrid dtgGrid)
        {
            string strFileHareError = "";

            ShowMessageToDataGrid(strErrorID, strCssClass, lblErrorDtg, dtgGrid, ref  strFileHareError);
        }
        public static void OpenNewWindow(System.Web.UI.Page pPage, string pURL, string pTitle)
        {
            string strScript = "<script language='JavaScript'>";
            strScript += "objShowDialog = window.open('" + pURL + "','" + pTitle + "');\n";
            strScript += "objShowDialog.focus();";
            strScript += "</script>";
            System.Web.UI.ScriptManager.RegisterClientScriptBlock(pPage, pPage.GetType(), "jscript", strScript, false);
        }
        public static void ShowMessageToDataGrid(string strErrorID, string strCssClass, string lblErrorDtg, DataGrid dtgGrid, ref string strFileHareError)
        {
            string[] arrID = strErrorID.Trim().Split('$');
            for (int k = 0; k < arrID.Length - 1; k++)
            {
                string strErr = arrID.GetValue(k).ToString().Trim();
                string[] arrIDs = strErr.Trim().Split('@');

                string strIDErr = arrIDs.GetValue(0).ToString().Trim();
                string strMessageErr = arrIDs.GetValue(1).ToString().Trim();

                dtgGrid.Items[Convert.ToInt16(strIDErr)].CssClass = strCssClass;
                ((Label)dtgGrid.Items[Convert.ToInt16(strIDErr)].FindControl(lblErrorDtg)).Text = strMessageErr;

                strFileHareError += dtgGrid.Items[Convert.ToInt16(strIDErr)].Cells[dtgGrid.Items[Convert.ToInt16(strIDErr)].Cells.Count - 1].Text + "$";
            }
        }
        public static SqlDbType ConvertDataType(string strTypeName)
        {
            SqlDbType TypeReturn = new SqlDbType();
            switch (strTypeName.Trim().ToUpper())
            {
                case "NVARCHAR":
                    TypeReturn = SqlDbType.NVarChar;
                    break;
                case "DATETIME":
                    TypeReturn = SqlDbType.NVarChar;
                    break;
                case "VARCHAR":
                    TypeReturn = SqlDbType.VarChar;
                    break;
                case "BIT":
                    TypeReturn = SqlDbType.Bit;
                    break;
                case "INT":
                    TypeReturn = SqlDbType.Int;
                    break;
                case "MONEY":
                    TypeReturn = SqlDbType.Money;
                    break;
                case "REAL":
                    TypeReturn = SqlDbType.Real;
                    break;
                case "NUMERIC":
                    TypeReturn = SqlDbType.Real;
                    break;
                case "SMALLINT":
                    TypeReturn = SqlDbType.SmallInt;
                    break;
                case "FLOAT":
                    TypeReturn = SqlDbType.Float;
                    break;
                default:
                    TypeReturn = SqlDbType.NVarChar;
                    break;
            }
            return TypeReturn;
        }
        public static int SafeDataInteger(Object pValue)
        {
            if ((pValue is DBNull))
            {
                return 0;
            }
            else if (Convert.ToString(pValue) == "")
            {
                return 0;
            }
            return Convert.ToInt32(pValue);
        }
        #region Import du lieu to Datagird
        /// <summary>
        /// Tanldt
        /// 16/09/2005
        /// Insert or update data
        /// </summary>
        /// <param name="strActivity">'Save' or 'Update'</param>
        /// <param name="Page">Page</param>
        /// <param name="strProcedureName">Store Prodedure Name</param>
        /// <returns>string</returns>		
        public static string ImportExcelTo_DataGrid(DataGrid dtgGrid, string pstrFilename)
        {

            string mstr_FileName = pstrFilename;

            if (!File.Exists(pstrFilename))
            {
                return "File not found, Please check path of the filename again!";
            }
            string mstr_PathFileName = mstr_FileName;
            //------------------

            string strConn;
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mstr_PathFileName + ";Extended Properties=Excel 8.0;";
            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
            DataSet myDataSet = new DataSet();
            myCommand.Fill(myDataSet, "ExcelData");

            DataTable dt = new DataTable();
            DataRow dr;

            int iCom = myDataSet.Tables["ExcelData"].Columns.Count;

            try
            {
                for (int j = 0; j < iCom; j++)
                {
                    string strDataColumn = myDataSet.Tables["ExcelData"].Rows[0][j].ToString().Trim();
                    dt.Columns.Add(new DataColumn(strDataColumn, typeof(string)));
                }
                for (int i = 1; i < myDataSet.Tables["ExcelData"].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    for (int j = 0; j < iCom; j++)
                    {
                        string strValue = myDataSet.Tables["ExcelData"].Rows[i][j].ToString().Trim();

                        dr[j] = strValue;
                    }
                    dt.Rows.Add(dr);
                }
                DataView dv = new DataView(dt);
                dtgGrid.DataSource = dv;
                dtgGrid.DataBind();
                dtgGrid.Columns[1].Visible = false;

                myDataSet.Dispose();
                return "Successful!";
            }
            catch (Exception exp)
            {
                myDataSet.Dispose();
                return exp.Message;
            }
        }
        #endregion
        public static string ImpactDB_ImportExcel(string strParamUserAction, Object strUserAction, string pstrFilename, string strActivity, string strProcedureName)
        {
            string mstr_FileName = pstrFilename;

            if (!File.Exists(pstrFilename))
            {
                return "File not found, Please check path of the filename again!";
            }
            string mstr_PathFileName = mstr_FileName;
            //------------------

            string strConn;
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mstr_PathFileName + ";Extended Properties=Excel 8.0;";
            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
            DataSet myDataSet = new DataSet();
            myCommand.Fill(myDataSet, "ExcelData");

            DataTable dtObj = new DataTable();
            dtObj = GetDataTable("sp_Common @ObjName=N'" + strProcedureName + "'");
            SqlTransaction sqlTran;
            SqlConnection cnn = new SqlConnection(ConfigurationSettings.AppSettings["strConnection"]);
            cnn.Open();
            sqlTran = cnn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = cnn;

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = strProcedureName;
            int iCom = myDataSet.Tables["ExcelData"].Columns.Count;
            try
            {
                #region Phan lay Ten Parameters tu dong dau cua file Excel
                for (int i = 1; i < myDataSet.Tables["ExcelData"].Rows.Count; i++)
                {
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@Activity", SqlDbType.NVarChar, 50).Value = strActivity.Trim();
                    cmd.Parameters.Add(strParamUserAction, SqlDbType.NVarChar, 10).Value = strUserAction;
                    for (int j = 0; j < iCom; j++)
                    {
                        //string[] strParam[i] = myDataSet.Tables["ExcelData"].Rows[0][i].ToString().Trim();
                        string a = myDataSet.Tables["ExcelData"].Rows[0][j].ToString().Trim();
                        DataRow[] iRow = dtObj.Select("columnname ='@" + myDataSet.Tables["ExcelData"].Rows[0][j].ToString().Trim() + "'");
                        if (iRow.Length > 0)
                        {
                            SqlParameter param = new SqlParameter();
                            param.ParameterName = iRow[0]["columnname"].ToString().Trim();

                            param.SqlDbType = ConvertDataType(iRow[0]["datatype"].ToString().Trim());
                            param.Size = SafeDataInteger(iRow[0]["size"].ToString().Trim());
                            //Value
                            string strValue = myDataSet.Tables["ExcelData"].Rows[i][j].ToString().Trim();

                            if (param.SqlDbType == SqlDbType.Real)
                                strValue = strValue.Replace(",", "");

                            if (strValue.Replace("&nbsp;", "").Trim() == "")
                                param.Value = DBNull.Value;
                            else
                            {
                                if (param.SqlDbType == SqlDbType.Bit)
                                    param.Value = (strValue == "True" || strValue == "1") ? 1 : 0;
                                else
                                    param.Value = strValue;
                            }

                            cmd.Parameters.Add(param);
                        }
                    }
                    cmd.ExecuteNonQuery();
                }

                #endregion
                if (sqlTran != null) sqlTran.Commit();
                myCommand.Dispose();
                myDataSet.Dispose();
                return "Successful!";
            }
            catch (Exception exp)
            {
                if (sqlTran != null) sqlTran.Rollback();
                myCommand.Dispose();
                myDataSet.Dispose();
                return exp.Message;
            }
        }
        //END---Long them Cho Chuc Nang IMPORT


        public static bool DeleteListRecordImage(string strStoreName, string strListID, string strImageColName, string strKey, string strPathConfig, Page page)
        {
            try
            {
                SQLHelper sqlHelper = new SQLHelper();
                string[] arrID = strListID.Trim().Split('$');
                string strSQl = "";
                DataTable dt = new DataTable();
                //--------------
                for (int i = 0; i < arrID.Length - 1; i++)
                {
                    /*
                        Lưu ý :Cấu trúc câu Delete trong DB phai Co Dang Nhu the nay
                     *      ELSE IF @Activity='Delete'
                                BEGIN
	                                SELECT ImageSampleName  -- De Lay ra cai ten File De delete trong Host
	                                  FROM TBL_ProductType WHERE ProductTypeID = @ProductTypeID
	                                Delete FROM TBL_ProductType
	                                WHERE ProductTypeID = @ProductTypeID
                                END
                     
                     */

                    sqlHelper.ClearAllParameters();
                    sqlHelper.AddParameter("@Activity", "Delete", SqlDbType.NVarChar);
                    sqlHelper.AddParameter("@" + strKey, arrID.GetValue(i), SqlDbType.Int);
                    dt = sqlHelper.ExecuteReader(strStoreName, CommandType.StoredProcedure);

                    /*strSQl += strStoreName + " @Activity='Delete'";
                    strSQl += ",@" + strKey + "=" + arrID.GetValue(i).ToString().Trim() + "";
                    dt = sqlHelper.GetDataTable(strSQl);*/

                    if (dt.Rows.Count > 0 && dt.Rows[0][strImageColName].ToString() != "")
                    {
                        DeleteImage(dt.Rows[0][strImageColName].ToString(), ConfigurationManager.AppSettings[strPathConfig].ToString(), page);
                        DeleteImage(dt.Rows[0][strImageColName].ToString().Substring(0, dt.Rows[0][strImageColName].ToString().LastIndexOf(".")) + "_Thumb" + dt.Rows[0][strImageColName].ToString().Substring(dt.Rows[0][strImageColName].ToString().LastIndexOf(".")), ConfigurationManager.AppSettings[strPathConfig].ToString(), page);
                    }
                    strSQl = "";
                }
                return true;
            }
            catch (Exception exp)
            {
                string strErr = exp.Message;
                return false;
            }
            finally
            {
            }
        }
        public static bool DeleteListRecord(string strStoreName, string strListID, string strKey)
        {
            try
            {
                SQLHelper sqlHelper = new SQLHelper();
                string[] arrID = strListID.Trim().Split('$');
                string strSQl = "";
                //--------------
                for (int i = 0; i < arrID.Length - 1; i++)
                {
                    /*HungDD comment out*/
                    /*strSQl += strStoreName + " @Activity='Delete'";
                    strSQl += ",@" + strKey + "=" + arrID.GetValue(i).ToString().Trim() + "";
                    sqlHelper.ExecuteCommand(strSQl);
                    strSQl = "";*/

                    sqlHelper.ClearAllParameters();
                    sqlHelper.AddParameter("@Activity", "Delete", SqlDbType.NVarChar);
                    sqlHelper.AddParameter("@" + strKey, arrID.GetValue(i), SqlDbType.Int);
                    sqlHelper.ExecuteScalar(strStoreName, CommandType.StoredProcedure);
                }
                return true;
            }
            catch (Exception exp)
            {
                string strErr = exp.Message;
                return false;
            }
            finally
            {
            }
        }
        public static DataTable GetDataTable(string pstrSQL)
        {
            string strErr = "";
            return GetDataTable(pstrSQL, ref strErr);
        }
        public static DataTable GetDataTable(string pstrSQL, ref string strErrOut)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection SQLconn = new SqlConnection(ConfigurationSettings.AppSettings["strConnection"]);
            DataTable rsData = new DataTable();
            SqlDataAdapter adpAdapter = new SqlDataAdapter();

            try
            {
                SQLconn.Open();
                cmd.Connection = SQLconn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = pstrSQL;
                cmd.CommandTimeout = 20000;

                adpAdapter.SelectCommand = cmd;
                adpAdapter.Fill(rsData);

                cmd.Dispose();
                SQLconn.Close();
                SQLconn.Dispose();
                adpAdapter.Dispose();
                return rsData;
            }
            catch (Exception exp)
            {
                cmd.Dispose();
                SQLconn.Close();
                SQLconn.Dispose();
                adpAdapter.Dispose();
                //string strErr = exp.Message;
                strErrOut = "Error GetDataTable: " + exp.Message;
                return null;
            }
        }
        public static string UploadImageVSThumb(FileUpload fupImage, string strKeyConfig, string strImageFixName, Page Page)
        {

            string strReturn = "";
            string strFileName = "";
            string mext = "";
            //Upload hinh vao Thu Muc Chua hinh
            string strPath = Page.Server.MapPath("~") + ConfigurationSettings.AppSettings[strKeyConfig].Trim();
            if (!System.IO.Directory.Exists(strPath))
            {
                strPath = Page.Server.MapPath("~"); //if folder ont created --> save in Root folder
            }
            //create random filename
            mext = fupImage.FileName.Substring(fupImage.FileName.LastIndexOf("."));
            strFileName = strImageFixName + DateTime.Now.Ticks + mext;
            if (File.Exists(strPath + strFileName))
                File.SetAttributes(strPath + strFileName, FileAttributes.Normal);
            fupImage.PostedFile.SaveAs(strPath + strFileName);
            strReturn = strFileName;


            //Save Thumb Image
            //System.Drawing.Image image = System.Drawing.Image.FromStream(fupImage.PostedFile.InputStream,true);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(fupImage.PostedFile.InputStream);
            string fileName = Path.Combine(strPath, fupImage.FileName);

            int imgWidth = (int)image.PhysicalDimension.Width;
            int imgHeight = (int)image.PhysicalDimension.Height;
            //float imgSize = imgHeight > imgWidth ? imgHeight : imgWidth;
            //float imgResize = imgSize <= 400 ? (float)(-10.0) : 400 / imgSize;
            //imgWidth *= imgResize; imgHeight *= imgResize;
            System.Drawing.Image thumb = image.GetThumbnailImage((int)(imgWidth * 0.2), (int)(imgHeight * 0.2), delegate() { return false; }, (IntPtr)(0));
            fileName = Path.Combine(
            strPath,
            string.Format("{0}_thumb{1}",
            Path.GetFileNameWithoutExtension(strFileName),
            Path.GetExtension(strFileName)
            )
            );

            if (File.Exists(fileName))
                File.Delete(fileName);
            thumb.Save(fileName);
            //End Save Thumb Image
            return strReturn;
        }
        public static string UploadImage(FileUpload fupImage, string strKeyConfig, string strImageFixName, Page Page)
        {
            strImageFixName = strImageFixName.Trim().Replace(" ", "_");
            string strReturn = "";
            string strFileName = "";
            string mext = "";
            //Upload hinh vao Thu Muc Chua hinh
            string strPath = Page.Server.MapPath("~") + ConfigurationSettings.AppSettings[strKeyConfig].Trim();
            if (!System.IO.Directory.Exists(strPath))
            {
                strPath = Page.Server.MapPath("~"); //if folder ont created --> save in Root folder
            }
            //create random filename
            mext = fupImage.FileName.Substring(fupImage.FileName.LastIndexOf("."));
            strFileName = strImageFixName + DateTime.Now.Ticks + mext;
            if (File.Exists(strPath + strFileName))
                File.SetAttributes(strPath + strFileName, FileAttributes.Normal);
            fupImage.PostedFile.SaveAs(strPath + strFileName);
            strReturn = strFileName;
            return strReturn;
        }
        public static string UploadImageFixedName(FileUpload fupImage, string strKeyConfig, string strImageFixName, Page Page) // Gán Tên Cứng
        {
            strImageFixName = strImageFixName.Trim().Replace(" ", "_");
            string strReturn = "";
            string strFileName = "";
            string mext = "";
            //Upload hinh vao Thu Muc Chua hinh
            string strPath = Page.Server.MapPath("~") + ConfigurationSettings.AppSettings[strKeyConfig].Trim();
            if (!System.IO.Directory.Exists(strPath))
            {
                strPath = Page.Server.MapPath("~"); //if folder ont created --> save in Root folder
            }
            //create random filename
            mext = fupImage.FileName.Substring(fupImage.FileName.LastIndexOf("."));
            strFileName = strImageFixName + mext;
            if (File.Exists(strPath + strFileName))
                File.SetAttributes(strPath + strFileName, FileAttributes.Normal);
            fupImage.PostedFile.SaveAs(strPath + strFileName);
            strReturn = strFileName;
            return strReturn;
        }
        public static void DeleteImage(string strFileName, string strFilePath, Page Page)
        {
            CommonFunction.DeleteImage(strFileName, strFilePath, Page);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pCtrl"></param>
        /// <param name="pCommandText"></param>
        /// <param name="pValueField"></param>
        /// <param name="pTextField"></param>
        /// <param name="pRowBlank"></param>
        public static string LoadDropDownListControl(DropDownList pCtrl, string pCommandText, string pValueField, string pTextField, bool pRowBlank)
        {
            try
            {
                SQLHelper sqlHelper = new SQLHelper();
                pCtrl.Items.Clear();
                DataTable dt = new DataTable();
                dt = sqlHelper.GetDataTable(pCommandText);
                int i;
                if (pRowBlank)
                    pCtrl.Items.Add("");

                if (dt != null)
                    for (i = 0; i < dt.Rows.Count; i++)
                    {
                        ListItem iTem = new ListItem(SafeDataString(dt.Rows[i][pTextField]), SafeDataString(dt.Rows[i][pValueField]));
                        pCtrl.Items.Add(iTem);
                    }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pValue"></param>
        /// <returns></returns>
        public static string SafeDataString(Object pValue)
        {
            if (pValue is DBNull)
            {
                return Convert.ToString(pValue);
            }
            int i;
            string str_Temp = Convert.ToString(pValue);
            string str_return = "";
            for (i = 0; i < str_Temp.Length; i++)
            {
                if (Convert.ToString(str_Temp[i]) == "'")
                {
                    str_return += "''";
                }
                else
                {
                    str_return += Convert.ToString(str_Temp[i]);
                }
            }
            return str_return;//Convert.ToString(pValue);//Replace(Convert.ToString(pValue), "'", "''");				
        }

        /*public static string SendMail(string strFrom, string strPass, string strTo, string strCC, string strBCC, string strSubject, string strBody)
        {
            string strReturn = "";
            string SMTPServer = ConfigurationSettings.AppSettings["smtpserver"].ToString();
            int SMTPServerPort = Convert.ToInt32(ConfigurationSettings.AppSettings["smtpserverport"].ToString());
            string _user = ConfigurationSettings.AppSettings["mail_account"].ToString();
            string _pass = ConfigurationSettings.AppSettings["mail_pass"].ToString();

            MailMessage mailMessage = new MailMessage();
            SmtpClient mailClient = new SmtpClient(SMTPServer, SMTPServerPort);
            mailClient.Timeout = 15000;
            mailClient.Credentials = new NetworkCredential(_user, _pass);
            mailClient.EnableSsl = true;

            mailMessage.IsBodyHtml = true;
            mailMessage.From = new MailAddress(strFrom);
            mailMessage.Subject = strSubject;
            mailMessage.Body = strBody;
            mailMessage.To.Add(strTo);
            try
            {
                mailClient.Send(mailMessage);
                strReturn = "Mail đến " + strTo + " thành công!";
                return strReturn;
            }
            catch (Exception ex)
            {
                return "Error, Send mail error: " + ex.ToString();
            }
        }*/

        public static string SendMail(string strFrom, string strPass, string strTo, string strCC, string strBCC, string strSubject, string strBody)
        {
            string strReturn = "";

            try
            {
                string SMTPServer = ConfigurationSettings.AppSettings["smtpserver"].ToString();
                int SMTPServerPort = Convert.ToInt32(ConfigurationSettings.AppSettings["smtpserverport"].ToString());
                string _user = ConfigurationSettings.AppSettings["mail_account"].ToString();
                string _pass = ConfigurationSettings.AppSettings["mail_pass"].ToString();

                MailMessage mail = new MailMessage();

                mail.From = _user;
                mail.To = strTo;

                mail.Subject = strSubject;
                mail.Body = strBody;
                mail.BodyFormat = MailFormat.Html;
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.Priority = MailPriority.Normal;

                if (strReturn == "")
                {
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", SMTPServer);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", SMTPServerPort);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _user);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _pass);
                    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

                    SmtpMail.Send(mail);
                    strReturn = "Mail đến " + strTo + " thành công!";
                }

                mail = null;
                return strReturn;
            }
            catch (Exception ex)
            {
                return "Error, Send mail error: " + ex.ToString();
            }
        }

        public static void GetAllControl(Control pRootCtl)
        {
            try
            {
                foreach (Control Child_ctl in pRootCtl.Controls)
                {

                    if (Child_ctl.HasControls() == true && Child_ctl.GetType().ToString().Trim().Substring(Child_ctl.GetType().ToString().Trim().LastIndexOf(".") + 1).ToString().Trim().ToUpper() != "CHECKBOXLIST")
                    //if(Child_ctl.HasControls()==true)
                    {
                        GetAllControl(Child_ctl);
                    }
                    else
                    {
                        string mCtlType = Child_ctl.GetType().ToString().Trim().Substring(Child_ctl.GetType().ToString().Trim().LastIndexOf(".") + 1).ToString().Trim();
                        if ((mCtlType.ToUpper() == "TEXTBOX"
                                || mCtlType.ToUpper() == "CHECKBOX"
                                || mCtlType.ToUpper() == "RADIOBUTTONLIST"
                                || mCtlType.ToUpper() == "DROPDOWNLIST"
                                || mCtlType.ToUpper() == "RADIOBUTTON"
                                || mCtlType.ToUpper() == "CHECKBOXLIST"
                                || mCtlType.ToUpper() == "HTMLIMAGE"
                                || mCtlType.ToUpper() == "MYDROPDOWNLISTCONTROL")
                            && (Child_ctl.ID.Trim().ToUpper() != "CHKSELECT"))

                            if (Child_ctl.ID.Trim().Length > 3)
                                strControl += Child_ctl.ID.Trim() + "$";
                    }
                }
            }
            catch (Exception exp)
            {
                string strError = exp.Message.ToString();
            }
        }

        public static void GetControl(Control pRootCtl, string strControlID, ref Control foundControl)
        {
            try
            {
                for (int i = 0; i < pRootCtl.Controls.Count; i++)
                {
                    if (pRootCtl.Controls[i].HasControls() == true)
                    {
                        string ctrlType = pRootCtl.Controls[i].GetType().ToString();
                        if (ctrlType == "System.Web.UI.HtmlControl")
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                        else //"System.Web.UI.HtmlControl"
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                    }
                    else
                    {
                        string strid = pRootCtl.Controls[i].ID;
                        if (strid != null && strid.ToUpper() == strControlID.ToUpper())
                            foundControl = pRootCtl.Controls[i];
                    }
                }
            }
            catch (Exception exp)
            {
                foundControl = null;
            }
        }

        public static void GetControl(HtmlControl pRootCtl, string strControlID, ref Control foundControl)
        {
            try
            {
                for (int i = 0; i < pRootCtl.Controls.Count; i++)
                {
                    if (pRootCtl.Controls[i].HasControls() == true)
                    {
                        string ctrlType = pRootCtl.Controls[i].GetType().ToString();
                        if (ctrlType == "System.Web.UI.HtmlControl")
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                        else //"System.Web.UI.HtmlControl"
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                    }
                    else
                    {
                        string strid = pRootCtl.Controls[i].ID;
                        if (strid != null && strid.ToUpper() == strControlID.ToUpper())
                            foundControl = pRootCtl.Controls[i];
                    }
                }
            }
            catch (Exception exp)
            {
                foundControl = null;
            }
        }

        public static void GetControl(Control pRootCtl, string strControlID, ref HtmlControl foundControl)
        {
            try
            {
                for (int i = 0; i < pRootCtl.Controls.Count; i++)
                {
                    if (pRootCtl.Controls[i].HasControls() == true)
                    {
                        string ctrlType = pRootCtl.Controls[i].GetType().ToString();
                        if (ctrlType == "System.Web.UI.HtmlControl")
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                        else //"System.Web.UI.HtmlControl"
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                    }
                    else
                    {
                        string strid = pRootCtl.Controls[i].ID;
                        if (strid != null && strid.ToUpper() == strControlID.ToUpper())
                            foundControl = (HtmlControl)pRootCtl.Controls[i];
                    }
                }
            }
            catch (Exception exp)
            {
                foundControl = null;
            }
        }

        public static void GetControl(HtmlControl pRootCtl, string strControlID, ref HtmlControl foundControl)
        {
            try
            {
                for (int i = 0; i < pRootCtl.Controls.Count; i++)
                {
                    if (pRootCtl.Controls[i].HasControls() == true)
                    {
                        string ctrlType = pRootCtl.Controls[i].GetType().ToString();
                        if (ctrlType == "System.Web.UI.HtmlControl")
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                        else //"System.Web.UI.HtmlControl"
                        {
                            GetControl(pRootCtl.Controls[i], strControlID, ref foundControl);
                        }
                    }
                    else
                    {
                        string strid = pRootCtl.Controls[i].ID;
                        if (strid != null && strid.ToUpper() == strControlID.ToUpper())
                            foundControl = (HtmlControl)pRootCtl.Controls[i];
                    }
                }
            }
            catch (Exception exp)
            {
                foundControl = null;
            }
        }


        public static void SetDataToControl(Control rptCtrl, string strCtrl, string value_)
        {
            try
            {
                Control ctrFound = rptCtrl.FindControl(strCtrl);
                if (ctrFound != null)
                {
                    string strType = ctrFound.GetType().ToString().Trim().Substring(ctrFound.GetType().ToString().Trim().LastIndexOf(".") + 1).ToString().Trim();
                    switch (strType)
                    {
                        case "TextBox":
                            ((TextBox)ctrFound).Text = value_;
                            break;
                        case "Label":
                            ((Label)ctrFound).Text = value_;
                            break;
                        case "DropDownList":
                            ((DropDownList)ctrFound).SelectedValue = value_;
                            break;
                        case "RadioButtonList":
                            ((RadioButtonList)ctrFound).SelectedValue = value_;
                            break;
                        case "HtmlImage":
                            ((HtmlImage)ctrFound).Src = value_;
                            break;
                        case "CheckBoxList":
                            int length = ((CheckBoxList)ctrFound).Items.Count;
                            char[] IsChecked = value_.ToCharArray();
                            for (int i = 0; i < length; i++)
                            {
                                if (IsChecked[i] == '1')
                                    ((CheckBoxList)ctrFound).Items[i].Selected = true;
                                else
                                    ((CheckBoxList)ctrFound).Items[i].Selected = false;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception err)
            {
                return;
            }
        }

        public static string GetHeightFromFileName(string FileName)
        {
            string strExtension = FileName.Substring(FileName.LastIndexOf("."));
            if (strExtension == "") return ""; //invalid file

            string[] str = FileName.Replace(strExtension, "").Split('_');
            if (str.Length >= 2)
            {
                return "height='" + str[str.Length - 1] + "'";
            }
            else
            {
                return "";
            }
        }

        public static string GetWidthFromFileName(string FileName)
        {
            string strExtension = FileName.Substring(FileName.LastIndexOf("."));
            if (strExtension == "") return ""; //invalid file

            string[] str = FileName.Replace(strExtension, "").Split('_');
            if (str.Length >= 2)
            {
                return "width='" + str[str.Length - 2] + "'";
            }
            else
            {
                return "";
            }
        }
    }

    public class StringUtil
    {
        private static readonly string[] VietnameseSigns = new string[]
        {

            "aAeEoOuUiIdDyY",

            "áàạảãâấầậẩẫăắằặẳẵ",

            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",

            "ễéèẹẻẽêếềệể",

            "ÉÈẸẺẼÊẾỀỆỂỄ",

            "óòọỏõôốồộổỗơớờợởỡ",

            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",

            "úùụủũưứừựửữ",

            "ÚÙỤỦŨƯỨỪỰỬỮ",

            "íìịỉĩ",

            "ÍÌỊỈĨ",

            "đ",

            "Đ",

            "ýỳỵỷỹ",

            "ÝỲỴỶỸ"

        };



        public static string RemoveSign4VietnameseString(string str)
        {
            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi
            for (int i = 1; i < VietnameseSigns.Length; i++)
            {
                for (int j = 0; j < VietnameseSigns[i].Length; j++)
                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            return str;
        }

        public static string Filter(string str)
        {
            str = str.ToString().Trim();
            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi
            for (int i = 1; i < VietnameseSigns.Length; i++)
            {
                for (int j = 0; j < VietnameseSigns[i].Length; j++)
                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            str = str.Trim();
            string[] signs_01 = { " ", "_", "&" };
            string[] signs_02 = { ".", "'", "\"", ":", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "{", "}", "[", "]", "\\", ";", "<", ">", "?", "/", ",", "=", "~", "`", "“", "”" };

            /*
            str = str.Replace(" ", "-");
            str = str.Trim();
            str = str.Replace("_", "-");
            str = str.Trim();
            str = str.Replace("&", "-");
            str = str.Trim();

            str = str.Replace(".", "");
            str = str.Trim();
            str = str.Replace("'", "");
            str = str.Trim();
            str = str.Replace("\"", "");
            str = str.Trim();
            str = str.Replace(":", "");
            str = str.Trim();
            */

            for (int i = 0; i < signs_01.Length; i++)
            {
                str = str.Replace(signs_01[i], "-");
                str = str.Trim();
            }

            for (int i = 0; i < signs_02.Length; i++)
            {
                str = str.Replace(signs_02[i], "");
                str = str.Trim();
            }

            if (str.StartsWith("-")) str = str.Substring(1);
            if (str.EndsWith("-")) str = str.Substring(0, str.Length - 1);
            return str.ToLower();
        }
        public static void Sort(int index, string action, string table, string fieldSort, string fieldID)
        {
            try
            {
                SQLHelper sql = new SQLHelper();
                string idFirst = "";
                string idSecont = "";
                DataTable dt = sql.GetDataTable("Select * from " + table + " ORDER BY " + fieldSort + " DESC");
                if (action == "UP")
                {
                    idFirst = dt.Rows[index][fieldID].ToString();
                    try
                    {
                        idSecont = dt.Rows[index - 1][fieldID].ToString();
                    }
                    catch (Exception ex)
                    {
                        idSecont = dt.Rows[index][fieldID].ToString();
                    }
                }
                if (action == "DOWN")
                {
                    idFirst = dt.Rows[index][fieldID].ToString();
                    try
                    {
                        idSecont = dt.Rows[index + 1][fieldID].ToString();
                    }
                    catch (Exception ex)
                    {
                        idSecont = dt.Rows[index][fieldID].ToString();
                    }
                }
                sql.ExecuteCommand("SYS_Paging @Activity='Sort',@Table='" + table + "',@FieldRank='" + fieldSort + "',@FieldID='" + fieldID + "',@IDFirst='" + idFirst + "',@IDSecount='" + idSecont + "'");

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string FilterSignWithoutSpace(string str)
        {
            str = str.Trim();
            string[] signs_01 = { " ", "_", "&" };
            string[] signs_02 = { ".", "'", "\"", ":", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "{", "}", "[", "]", "\\", ";", "<", ">", "?", "/", ",", "=", "~", "`", "“", "”" };

            for (int i = 0; i < signs_01.Length; i++)
            {
                str = str.Replace(signs_01[i], "-");
                str = str.Trim();
            }

            for (int i = 0; i < signs_02.Length; i++)
            {
                str = str.Replace(signs_02[i], "");
                str = str.Trim();
            }

            if (str.StartsWith("-")) str = str.Substring(1);
            if (str.EndsWith("-")) str = str.Substring(0, str.Length - 1);
            return str;
        }
    }

}
